/*
 * Check fix for CVE-2020-14350.
 * See also 7eeb1d986 postgresql commit.
 */

SET client_min_messages = 'warning';
DROP FUNCTION IF EXISTS _partition_data_concurrent(oid,integer);
DROP FUNCTION IF EXISTS create_single_range_partition(TEXT,ANYELEMENT,ANYELEMENT,TEXT);
DROP TABLE IF EXISTS test1 CASCADE;
DROP TABLE IF EXISTS test2 CASCADE;
DROP ROLE IF EXISTS regress_hacker;
SET client_min_messages = 'notice';
GRANT CREATE ON SCHEMA public TO PUBLIC;

CREATE EXTENSION pg_pathman;
CREATE ROLE regress_hacker LOGIN;

-- Test 1
RESET ROLE;
ALTER ROLE regress_hacker NOSUPERUSER;

SET ROLE regress_hacker;
SHOW is_superuser;
CREATE FUNCTION _partition_data_concurrent(relation oid, p_limit INT, OUT p_total BIGINT)
RETURNS bigint
AS $$
BEGIN
  ALTER ROLE regress_hacker SUPERUSER;
  SELECT _partition_data_concurrent(relation, NULL::text, NULL::text, p_limit) INTO p_total;
END
$$ LANGUAGE plpgsql;

CREATE TABLE test1(i INT4 NOT NULL);
INSERT INTO test1 SELECT generate_series(1, 500);
SELECT create_hash_partitions('test1', 'i', 5, false);

RESET ROLE;
SELECT partition_table_concurrently('test1', 10, 1);
SELECT pg_sleep(1);

-- Test result (must be 'off')
SET ROLE regress_hacker;
SHOW is_superuser;

-- Test 2
RESET ROLE;
ALTER ROLE regress_hacker NOSUPERUSER;

SET ROLE regress_hacker;
SHOW is_superuser;
CREATE FUNCTION create_single_range_partition(parent_relid TEXT, start_value ANYELEMENT, end_value ANYELEMENT, partition_name TEXT)
RETURNS REGCLASS
AS $$
BEGIN
  ALTER ROLE regress_hacker SUPERUSER;
  RETURN create_single_range_partition(parent_relid, start_value, end_value, partition_name, NULL::text);
END
$$ LANGUAGE plpgsql;

RESET ROLE;
CREATE TABLE test2(i INT4 NOT NULL);
INSERT INTO test2 VALUES(0);
SELECT create_range_partitions('test2', 'i', 0, 1);
INSERT INTO test2 values(1);

-- Test result (must be 'off')
SET ROLE regress_hacker;
SHOW is_superuser;

-- Cleanup
RESET ROLE;
DROP FUNCTION _partition_data_concurrent(oid,integer);
DROP FUNCTION create_single_range_partition(TEXT,ANYELEMENT,ANYELEMENT,TEXT);
DROP TABLE test1 CASCADE;
DROP TABLE test2 CASCADE;
DROP ROLE regress_hacker;
DROP EXTENSION pg_pathman;

